package com.hospital.utils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;

public class FlaskArimaClient {

    public static void main(String[] args) {
        try {
            // 构建请求数据
            JSONObject jsonData = new JSONObject();
            jsonData.put("steps", 5);  // 预测未来 5 个时间点

            // 创建 URL 对象
            URL url = new URL("http://localhost:5000/predict");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法和请求头
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "application/json");
            connection.setDoOutput(true);

            // 发送请求数据
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonData.toString().getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            // 读取响应
            int status = connection.getResponseCode();
            InputStream is = (status >= 200 && status < 300) ? connection.getInputStream() : connection.getErrorStream();

            BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
            StringBuilder response = new StringBuilder();
            String responseLine;

            while ((responseLine = br.readLine()) != null) {
                response.append(responseLine.trim());
            }

            // 处理响应
            if (status == 200) {
                JSONObject jsonResponse = new JSONObject(response.toString());
                System.out.println("Predictions: " + jsonResponse.getJSONArray("predictions"));
            } else {
                System.out.println("Request failed with status code: " + status);
                System.out.println("Response: " + response.toString());
            }

            connection.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}